package com.tanhua.dubbo.api;

import cn.hutool.core.util.ObjectUtil;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Visitors visitors) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        boolean exists = mongoTemplate.exists(query, Visitors.class);
        if (!exists) {
            mongoTemplate.save(visitors);
        }
    }

    @Override
    public List<Visitors> findById(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "date"));
        return mongoTemplate.find(query, Visitors.class);
    }

    @Override
    public List<Visitors> queryMyVisitor(Long userId,Long date) {

        // 查询前5个访客数据，按照访问时间倒序排序
        // 如果用户已经查询过列表，记录查询时间，后续查询需要按照这个时间往后查询
        // 上一次查询列表的时间
//        Long date = Convert.toLong(redisTemplate.opsForHash().get(VISITOR_REDIS, String.valueOf(userId)));

        PageRequest pageRequest = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(pageRequest);
        if (ObjectUtil.isNotEmpty(date)) {
            query.addCriteria(Criteria.where("date").gte(date));
        }

        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);
        //查询每个来访用户的得分
        for (Visitors visitors : visitorsList) {

            Query queryScore = Query.query(Criteria.where("toUserId")
                    .is(userId).and("userId").is(visitors.getVisitorUserId())
            );
            RecommendUser recommendUser = this.mongoTemplate.findOne(queryScore, RecommendUser.class);
            if (ObjectUtil.isNotEmpty(recommendUser)) {
                visitors.setScore(recommendUser.getScore());
            } else {
                //默认得分
                visitors.setScore(90d);
            }
        }

        return visitorsList;
    }
}

